<?php
/**
 * Author: Administrator
 * Date: 2022/7/28 1:02
 */

namespace DesignPatterns\Behavioral\Observer;

class User implements \SplSubject
{
    protected \SplObjectStorage $listeners;
    protected string $name;
    protected int $age;

    public function __construct($name, $age)
    {
        $this->name = $name;
        $this->age = $age;
        $this->listeners = new \SplObjectStorage();
    }

    /**
     * @inheritDoc
     */
    public function attach(\SplObserver $observer): void
    {
        $this->listeners->attach($observer);
    }

    /**
     * @inheritDoc
     */
    public function detach(\SplObserver $observer): void
    {
        $this->listeners->detach($observer);
    }

    /**
     * @inheritDoc
     */
    public function notify(): void
    {
        $argv = func_get_args();
        if ($argv) {
            $event = $argv[0];
        } else {
            $event = '';
        }
        foreach ($this->listeners as $listener) {
            /**
             * @var \SplObserver $listener
             */
            if ($listener::EVENT == $event) {
                $listener->update($this);
            }
        }
    }

    public function getName(): string
    {
        return $this->name;
    }

    public function getAge(): int
    {
        return $this->age;
    }

    public function __set($name, $value)
    {
        if (isset($this->$name)) {
            $this->$name = $value;
            $this->notify($name);
        }
    }
}